package cn.bone.springDemo.test02.dao;

import cn.bone.springDemo.test02.bean.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;
import java.util.UUID;

/**
 * Created by superbone on 2018/9/4.
 */
@Repository
public class UserDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    public void insert(){
        String sql = "insert into my_user (name,age) values(?,?)";

        String name = UUID.randomUUID().toString().substring(0,5);
        Random random = new Random();
        int age = random.nextInt(10)+10;
        jdbcTemplate.update(sql,name,age);
    }

    public User get(int id){
        String sql = "select * from my_user t where t.id = ?";
//        User user = jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
//            @Override
//            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
//                User user = new User();
//                return user;
//            }
//        }, id);

        User user = jdbcTemplate.queryForObject(sql, (ResultSet rs, int rowNum)-> {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                u.setAge(rs.getInt("age"));
                return u;
            },id);
        return user;
    }
}
